<?php

namespace App\Http\Controllers;

use App\Models\Role;
use App\Models\RolePermission;
use App\Models\UserRole;
use App\Models\Users;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class RolesController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        //
        $name  = $request->get("name");

        $pageNum  = $request->get("page_num");
        $pageSize  = $request->get("page_size",1000);
        $where = [];
        $role = Role::when($name, function ($query) use ($name) {
            $name = str_replace(" ","",strtolower($name));
            return $query->where('name', "like", "%" . $name . "%");
        })
            ->where($where)
            ->paginate($pageSize,['*'],"page",$pageNum);
        $list = $role->getCollection();
        return Success(10100,["data"=>$list,"page_info"=>['current'=>$role->currentPage(),'page_size'=>(int)$pageSize,"count"=>$role->total(),"pages"=>$role->lastPage()]]);
    }



    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        //
        $name = $request->get("name");
        $permission = $request->get("permission");
        if (!$name) {
            return Failed(10002, ["File" => "RoleController", "line" => __LINE__, "need_filed" => ['role_name']]);
        }

        if(empty($permission)){
            return Failed(10002, ["File" => "RoleController", "line" => __LINE__, "need_filed" => ['permission']]);
        }
        $role = Role::where("name", $name)->first();
        if ($role) {
            return Failed(10006, ['File' => "RoleController", "line" => __LINE__, "resource_same" => $name]);
        }

        $role = new Role();
        $role->name = $name;
        $role->status = 1;
        $role->updated_at = date("Y-m-d H:i:s");
        $role->created_at = date("Y-m-d H:i:s");
        if (!$role->save()) {
            return Failed(10001, ['File' => "RoleController", "line" => __LINE__]);
        }
        $role_per_data = [];
        foreach ($permission as $vo){
            $role_per_data [] = [
                'role_id'=>$role->id,
                'permission_id'=>$vo,
                'updated_at' =>date("Y-m-d H:i:s"),
                'created_at' =>date("Y-m-d H:i:s"),
            ];
        }
        if(!RolePermission::insert($role_per_data)){
            return Failed(10001, ['File' => "RoleController", "line" => __LINE__]);
        }

        return Success(10000, []);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return JsonResponse
     */
    public function show(int $id): JsonResponse
    {
        //
        if(!$id){
            return Failed(10002, ["File"=>"RolesController","line"=>__LINE__,"need_filed" => ['id']]);
        }
        $role = Role::where([["id",$id]])->first();
        $permission = $role->permissions->toArray();

        if(!$role){
            return Failed(11101, ["File"=>"RolesController","line"=>__LINE__,"resources" => "not_found"]);
        }
        return Success(11100,["data"=>$role,"permission"=>$permission]);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return JsonResponse
     */
    public function update(Request $request, int $id): JsonResponse
    {
        //
        if(!$id){
            return Failed(10002, ["File"=>"RolesController","line"=>__LINE__,"need_filed" => ['id']]);
        }
        $status = $request->get("status",1);
        $name = $request->get("name");
        $permissions = $request->get("permission");
        if(!$permissions){
            return Failed(10002, ["File"=>"RolesController","line"=>__LINE__,"need_filed" => ['permission']]);
        }
        $role = Role::where([["id",$id]])->first();
        if(!$role){
            return Failed(10005, ["File"=>"RolesController","line"=>__LINE__,"resources" => "not_found"]);
        }
        $role ->name = $name;
        $role ->status = $status;
        $role ->updated_at = date("Y-m-d H:i:s");
        RolePermission::where("role_id",$id)->delete();
        if(!$role->save()){
            return Failed(11010, ["File"=>"RolesController","line"=>__LINE__,"resources" =>"updated_error"]);
        }
        foreach ($permissions as $key => $vo) {
            $data[$key] = [
                "role_id" => $id,
                "permission_id" => $vo,
                "updated_at" => date("Y-m-d H:i:s"),
                "created_at" => date("Y-m-d H:i:s"),
            ];
        }
        try {
            if (!RolePermission::insert($data)) {
                return Failed(10001, ['File' => "RolesController", "line" => __LINE__, "msg" => "角色绑定权限失败"]);
            }
        } catch (\Illuminate\Database\QueryException $ex) {
            return Failed(10006, ['File' => "RolesController", "line" => __LINE__, "resource_same" => $data]);
        }
        return Success(11000, ["File"=>"RolesController","line"=>__LINE__,"resources" =>"updated_success"]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return JsonResponse
     */
    public function destroy(int $id): JsonResponse
    {
        //
        if(!$id){
            return Failed(10002, ["File"=>"RolesController","line"=>__LINE__,"need_filed" => ['id']]);
        }
        $role = Role::where([["id",$id],['status',1]])->first();
        if(!$role){
            return Failed(10005, ["File"=>"RolesController","line"=>__LINE__,"resources" => "not_found"]);
        }
        Role::where("id",$id)->delete();
        RolePermission::where("role_id",$id)->delete();
        UserRole::where("role_id",$id)->delete();
        return Success(10700, ["File"=>"RolesController","line"=>__LINE__,"resources" => "delete_fsuccess"]);
    }

    /**
     * @param  Request  $request
     * @return JsonResponse
     */
    public function bindPermission(Request $request,$role_id): JsonResponse
    {

        $permissionArr = $request->get("permissionArr");
        if (!$role_id  || empty($permissionArr)) {
            return Failed(10002, ["File" => "RoleController", "line" => __LINE__, "need_filed" => ['role_id', 'permissionArr']]);
        }
        RolePermission::where("role_id",$role_id)->delete();
        $data = [];

        foreach ($permissionArr as $key => $vo) {
            $data[$key] = [
                "role_id" => $role_id,
                "permission_id" => $vo,
                "updated_at" => date("Y-m-d H:i:s"),
                "created_at" => date("Y-m-d H:i:s"),
            ];
        }
        try {
            if (!RolePermission::insert($data)) {
                return Failed(10001, ['File' => "RolesController", "line" => __LINE__, "msg" => "角色绑定权限失败"]);
            }
        } catch (\Illuminate\Database\QueryException $ex) {
            return Failed(10006, ['File' => "RolesController", "line" => __LINE__, "resource_same" => $data]);
        }

        return Success(10000, []);
    }
}
